<!--  -->
<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    >
    </el-switch>
    <el-button
      type="success"
      v-if="updateNodes.length > 0"
      @click="batchSave"
      plain
      >拖拽保存</el-button
    >
    <el-button type="danger" plain @click="batchDelete">批量删除</el-button>
    <el-tree
      @node-drop="handleDrop"
      :allow-drop="allowDrop"
      :draggable="draggable"
      :default-expanded-keys="expandeKey"
      node-key="catId"
      show-checkbox
      :expand-on-click-node="false"
      :data="menus"
      :props="defaultProps"
      @node-click="handleNodeClick"
      @node-expand="nodeExpand"
      @node-collapse="nodeCollapse"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            <i class="el-icon-plus"></i>
          </el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">
            <i class="el-icon-edit"></i>
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            <i class="el-icon-delete"></i>
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量名称">
          <el-input
            placeholder="例如：个"
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">{{
          submitText
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    return {
      draggable: false,
      pCid: 0,
      updateNodes: [],
      maxLevel: 0,
      submitText: "",
      title: "",
      // add\ edit
      dialogType: "",
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        productUnit: "",
        catId: null,
        icon: "",
      },
      dialogVisible: false,
      expandeKey: [],
      menus: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    batchDelete() {
      let catIds = [];
      let catNames = [];
      let checkedNodes = this.$refs.menuTree.getCheckedNodes();
      // console.log("被选中的元素：", checkedNodes);
      for (let i = 0; i < checkedNodes.length; i++) {
        catIds.push(checkedNodes[i].catId);
        catNames.push(checkedNodes[i].name);
      }
      this.confirmOpen(
        `是否批量删除【${catNames}】菜单`,
        () => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false),
          }).then(({ data }) => {
            this.successOpen("菜单批量删除成功！！");
            this.getMenus();
          });
        },
        () => {}
      );
    },
    batchSave() {
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      })
        .then(({ data }) => {
          this.successOpen("拖拽修改成功");
          this.updateNodes = [];
          this.pCid = 0;
          this.maxLevel = 0;
          this.getMenus();
        })
        .catch(({ data }) => {
          this.failOpen(`抱歉，服务器异常,${data}`);
        });
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      // console.log("handleDrop: ", draggingNode, dropNode, dropType, ev);
      // 当前最新节点的父节点id
      let pCid = 0;
      let sibings = null;
      if (dropType == "before" || dropType == "after") {
        pCid = dropNode.parent.data.catId || 0;
        sibings = dropNode.parent.childNodes;
      } else {
        pCid = dropNode.data.catId;
        sibings = dropNode.childNodes;
      }
      this.pCid = pCid;
      // 当前最新节点的排序
      for (let i = 0; i < sibings.length; i++) {
        if (sibings[i].data.catId == draggingNode.data.catId) {
          // 如果遍历的节点是当前拖拽的节点,增加改父 id,当前节点的层级发生变化
          this.updateNodes.push({
            catId: sibings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: sibings[i].level,
          });
          // 如果层级发生变化，其子集也要跟着变化
          if (sibings[i].level != draggingNode.level) {
            this.updateChildNodesLevel(sibings[i]);
          }
        } else {
          this.updateNodes.push({ catId: sibings[i].data.catId, sort: i });
        }
      }

      // 当前节点的最新层级
      this.ekidPush(this.pCid);

      // console.log("updateNodes", this.updateNodes);
    },
    ekidPush(cid) {
      for (let i = this.expandeKey.length - 1; i >= 0; i--) {
        if (this.expandeKey[i] == cid) {
          return;
        }
      }
      this.expandeKey.push(cid);
    },
    updateChildNodesLevel({ childNodes, level }) {
      if (childNodes.length > 0) {
        for (let i = 0; i < childNodes.length; i++) {
          // console.log(`遍历子集:${childNodes[i]}`);
          let cNode = childNodes[i].data;
          this.updateNodes.push({ catId: cNode.catId, catLevel: level + 1 });
          this.updateChildNodesLevel(childNodes[i]);
        }
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      this.maxLevel = 0;
      // 1.被拖动的当前结点以及所在的父节点总层数不能大于3
      // 1）、被拖拽的当前节点总层数
      console.log("当前节点", draggingNode, dropNode, type);
      // 得到当前节点的最大层级
      this.countNodeLevel(draggingNode);
      // 深度计算
      let deep = this.maxLevel - draggingNode.level + 1;
      // console.log("深度", deep, this.maxLevel, dropNode.level);
      if (type == "inner") {
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
    },
    countNodeLevel(node) {
      if (node.level > this.maxLevel) {
        this.maxLevel = node.level;
      }
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          this.countNodeLevel(node.childNodes[i]);
        }
      }
    },
    editCategory() {
      let { catId, name, icon, productUnit } = this.category;
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({ catId, name, icon, productUnit }, false),
      })
        .then(({ data }) => {
          // console.log(data);
          if (data.code == 0) {
            this.successOpen(`【${name}】菜单修改成功`);
            this.getMenus();
            this.dialogVisible = false;
          }else{
            this.failOpen(`修改发生错误，错误原因:${data.data.name}`);
          }
        })
        .catch(({ data }) => {
          // console.log(data);
          this.failOpen(`菜单修改失败，错误原因:${data.data.name}`);
        });
    },
    submitData() {
      if (this.dialogType == "add") {
        this.addCategory();
      }
      if (this.dialogType == "edit") {
        this.editCategory();
      }
    },
    edit(data) {
      this.submitText = "修 改";
      this.title = "修改分类";
      this.dialogType = "edit";
      // console.log("要修改的", data);
      // 发送请求获取最新数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        // 请求成功
        // console.log("回显数据",data)
        this.category.name = data.category.name;
        this.category.catId = data.category.catId;
        this.category.icon = data.category.icon;
        this.category.productUnit = data.category.productUnit;

        this.dialogVisible = true;
      });
      // this.category.name = data.name;
      // this.category.productUnit = data.productUnit;
      // this.category.catId = data.catId;
    },
    addCategory() {
      // console.log("提交的三级分类", this.category);
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      })
        .then(({ data }) => {
          this.successOpen(`【${this.category.name}】菜单保存成功~`);
          this.dialogVisible = false;
          this.ekidPush(this.category.parentCid);
          console.log(this.expandeKey);
          this.getMenus();
        })
        .catch((error) => {
          // console.log(error);
          this.failOpen(`菜单新增失败,分类名称不能为空`);
        });
    },
    nodeExpand(obj) {
      this.expandeKey.push(obj.catId);
    },
    nodeCollapse(obj) {
      this.expandeKey.splice(
        this.expandeKey.findIndex((item) => item.id === obj.catId),
        1
      );
    },
    handleNodeClick(data) {
      // console.log(data);
    },
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        // console.log("成功获取菜单数据", data.data);
        this.menus = data.data;
      });
    },
    append(data) {
      this.submitText = "添 加";
      this.title = "添加分类";
      this.dialogType = "add";
      this.category.name = "";
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.catId = null;
      this.category.sort = 0;
      this.category.showStatus = 1;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      // console.log("append", data);

      this.dialogVisible = true;
    },

    remove(node, data) {
      let ids = [data.catId];
      let su = () =>
        this.$http({
          url: this.$http.adornUrl("/product/category/delete"),
          method: "post",
          data: this.$http.adornData(ids, false),
        })
          .then(({ data }) => {
            // console.log("删除成功..");
            this.getMenus();
          })
          .then(this.successOpen(`【${data.name}】菜单，删除成功~`));
      this.confirmOpen(`是否删除【${data.name}】菜单`, su, () => {});
    },
    successOpen(message) {
      this.$message({
        message: message,
        type: "success",
      });
    },
    failOpen(message) {
      this.$message.error(message);
    },
    confirmOpen(message, su, ca) {
      this.$confirm(message, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(su)
        .catch(ca);
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getMenus();
    this.expandeKey = [];
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
</style>